package com.papper.mng.controller.sys;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.papper.common.bean.base.BaseConstIp;
import com.papper.common.bean.sys.SysAuth;
import com.papper.common.constant.SystemConstants;
import com.papper.common.enums.DataStatusEnum;
import com.papper.common.exception.ServiceException;
import com.papper.common.service.DwzPage;
import com.papper.common.service.sys.SysAuthService;
import com.papper.common.utils.tool.DateTool;
import com.papper.common.utils.tool.StringTool;
import com.papper.mng.controller.BaseAction;
import com.papper.mng.domain.DwzResponse;
import com.papper.mng.domain.excel.SysAuthExcelVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.StringUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @Author:Lajiao
 * @Date:2014年8月21日
 * @Time:下午12:42:13
 * @Description:系统授权
 */
@Controller
@RequestMapping("/sys/auth")
public class SysAuthController extends BaseAction {
    @Autowired
    SysAuthService sysAuthService;

    /**
     * 系统授权
     *
     * @return
     */
    @GetMapping(value = "")
    public String execute(HttpServletRequest _request, Model model) {
        // 字段查询条件
        Map<String, Object> objects = Maps.newHashMap();
        extraParams(objects, _request, BaseConstIp.class);
        modelParm(objects, model);
        // 分页查询条件
        int pageNum    = StringTool.parseInteger(_request.getParameter("pageNum"), 1);
        int numPerPage = StringTool.parseInteger(_request.getParameter("numPerPage"), SystemConstants.PAGE_LIMIT_16);
        // 数据查询
        Example           example = buildExample(objects, model, BaseConstIp.class);
        PageInfo<SysAuth> pageRtn = sysAuthService.findPage(pageNum, numPerPage, example);
        model.addAttribute("page", new DwzPage(pageNum, numPerPage, pageRtn.getTotal()));
        model.addAttribute("records", pageRtn.getList());
        return render("sys/auth/index");
    }

    /**
     * 系统授权_新增
     *
     * @throws IOException
     */
    @GetMapping(value = "/add")
    public String add_get() {
        return render("sys/auth/add");
    }

    @PostMapping(value = "/add")
    @ResponseBody
    public DwzResponse add_post(HttpServletRequest _request, HttpServletResponse _response, SysAuth sysAuth) {
        try {
            checkSuperCert(_request);
        } catch (ServiceException e) {
            return new DwzResponse("300", e.getMessage());
        }
        // 添加系统授权
        try {
            sysAuth.setAuthTime(new Date());
            sysAuth.setDataStatus(DataStatusEnum.OPEN.getCode());
            sysAuth.setCreateTime(new Date());
            sysAuth.setModifyTime(new Date());
            sysAuthService.save(sysAuth);
            return new DwzResponse("200", "系统授权添加成功!!!", "closeCurrent");
        } catch (Exception e) {
            e.printStackTrace();
            return new DwzResponse("300", "系统授权添加失败:" + e.getMessage() + "!!!");
        }
    }

    /**
     * 系统授权_更新
     *
     * @param id
     * @throws IOException
     */
    @GetMapping(value = "/edit")
    public String edti_get(Model model, Long id) {
        SysAuth entity = sysAuthService.findById(id);
        model.addAttribute("entity", entity);
        return render("sys/auth/edit");
    }

    @PostMapping(value = "/edit")
    @ResponseBody
    public DwzResponse edit_post(HttpServletRequest _request, HttpServletResponse _response, SysAuth sysAuth) {
        try {
            checkSuperCert(_request);
        } catch (ServiceException e) {
            return new DwzResponse("300", e.getMessage());
        }
        try {
            sysAuth.setModifyTime(new Date());
            sysAuthService.update(sysAuth);
            return new DwzResponse("200", "系统授权修改成功!!!", "closeCurrent");
        } catch (Exception e) {
            e.printStackTrace();
            return new DwzResponse("300", "系统授权修改失败:" + e.getMessage());
        }
    }

    /**
     * 系统授权_删除
     *
     * @param _response
     * @param id
     * @throws IOException
     */
    @PostMapping(value = "/del")
    @ResponseBody
    public DwzResponse del_post(HttpServletRequest _request, HttpServletResponse _response, Long id) {
        try {
            checkSuperCert(_request);
        } catch (ServiceException e) {
            return new DwzResponse("300", e.getMessage());
        }
        if (id == null || id.intValue() <= 0) {
            return new DwzResponse("300", "参数[id]为空！");
        }
        SysAuth old = sysAuthService.findById(id);
        if (old == null) {
            return new DwzResponse("300", "参数[id]信息异常！");
        }
        try {
            sysAuthService.deleteById(id);
            return new DwzResponse("200", "系统授权删除成功!!!");
        } catch (Exception e) {
            e.printStackTrace();
            return new DwzResponse("300", "系统授权删除失败:" + e.getMessage());
        }
    }

    /**
     * 系统授权_详情
     *
     * @return
     */
    @GetMapping(value = "/detail")
    public String detail(Model model, Long id) {
        SysAuth sysAuth = sysAuthService.findById(id);
        model.addAttribute("entity", sysAuth);
        return render("sys/auth/detail");
    }

    /**
     * 授权数据导入_新增
     *
     * @throws IOException
     */
    @GetMapping(value = "/import")
    public String import_get() {
        return render("sys/auth/import");
    }

    @PostMapping(value = "/import")
    @ResponseBody
    public DwzResponse import_post(HttpServletRequest _request, HttpServletResponse _response, @RequestParam MultipartFile file) throws IOException {
        try {
            checkVerifyCert(_request);
        } catch (ServiceException e) {
            return new DwzResponse("300", e.getMessage());
        }
        if (!file.getOriginalFilename().endsWith("xlsx")) {
            return new DwzResponse("300", "请上传格式xlsx的文件");
        }
        // 数据录入
        List<SysAuth>            addRecords = Lists.newArrayList();
        AtomicReference<Integer> succCount  = new AtomicReference<>(0);
        AtomicReference<Integer> failCount  = new AtomicReference<>(0);
        EasyExcel.read(file.getInputStream(), SysAuthExcelVo.class, new PageReadListener<SysAuthExcelVo>(dataList -> {
            for (SysAuthExcelVo data : dataList) {
                if (StringUtil.isEmpty(data.getAuthId()) || StringUtil.isEmpty(data.getAuthValue()) || StringUtil.isEmpty(data.getAuthDesc())) {
                    failCount.getAndSet(failCount.get() + 1);
                    continue;
                }
                SysAuth dbAuth = sysAuthService.findByAuthId(data.getAuthId());
                if (dbAuth != null) {
                    failCount.getAndSet(failCount.get() + 1);
                    continue;
                }
                SysAuth addAuth = new SysAuth();
                addAuth.setAuthType("MD5");
                addAuth.setAuthId(data.getAuthId());
                addAuth.setAuthValue(data.getAuthValue());
                addAuth.setAuthDesc(data.getAuthDesc());
                addAuth.setAuthTime(new Date());
                addAuth.setAuthAvailable(365);
                addAuth.setDataStatus(DataStatusEnum.OPEN.getCode());
                addAuth.setCreateTime(new Date());
                addAuth.setModifyTime(new Date());
                addRecords.add(addAuth);
                succCount.set(succCount.get() + 1);
            }
        })).sheet().doRead();
        try {
            sysAuthService.batchInsert(addRecords);
            return new DwzResponse("200", "密钥数据入库成功:[" + succCount + "] 失败:[" + failCount + "]!!!", "closeCurrent");
        } catch (Exception e) {
            e.printStackTrace();
            return new DwzResponse("300", "密钥数据入库失败:" + e.getMessage() + "!!!");
        }
    }

    /**
     * 交易明细_导出明细
     *
     * @return
     */
    @RequestMapping(value = "/excel")
    public void excel(HttpServletRequest _request, HttpServletResponse _response) throws IOException {
        try {
            checkSuperCert(_request);
        } catch (ServiceException e) {
            e.printStackTrace();
            return;
        }
        // 读取数据
        List<List<String>> records  = new ArrayList<>();
        Example            conditon = new Example(SysAuth.class);
        int                maxRow   = 0;
        int                limit    = 2000;
        int                start    = 0;
        PageInfo<SysAuth>  pageRtn  = sysAuthService.findPage(start, limit, conditon);
        while (maxRow < 50000 && pageRtn != null && (pageRtn.getList() != null && pageRtn.getList().size() > 0)) {
            for (SysAuth sysAuth : pageRtn.getList()) {
                records.add(excelRecord(sysAuth));
                maxRow++;
            }
            start = start + 1;
            pageRtn = sysAuthService.findPage(start, limit, conditon);
        }
        // 导出数据
        _response.setContentType("application/vnd.ms-excel");
        _response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode(DateTool.formatDate(new Date(), DateTool.FULL_PATTERN), "UTF-8");
        _response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        EasyExcel.write(_response.getOutputStream(), SysAuth.class).sheet(DateTool.getShortNow()).head(excelTitle()).doWrite(records);
    }

    private List<List<String>> excelTitle() {
        List<List<String>> head = new ArrayList<>();
        head.add(Lists.newArrayList("授权方式"));
        head.add(Lists.newArrayList("授权ID"));
        head.add(Lists.newArrayList("授权值"));
        head.add(Lists.newArrayList("授权用户"));
        head.add(Lists.newArrayList("授权系统"));
        head.add(Lists.newArrayList("授权软件"));
        head.add(Lists.newArrayList("授权版本"));
        head.add(Lists.newArrayList("授权时间"));
        head.add(Lists.newArrayList("授权有效期"));
        head.add(Lists.newArrayList("授权IP地址"));
        head.add(Lists.newArrayList("授权浏览器"));
        return head;
    }

    private List<String> excelRecord(SysAuth sysAuth) {
        List<String> rowData = Lists.newArrayList();
        rowData.add(sysAuth.getAuthType());
        rowData.add(sysAuth.getAuthId());
        rowData.add(sysAuth.getAuthValue());
        rowData.add(sysAuth.getAuthDesc());
        rowData.add(sysAuth.getAuthOs());
        rowData.add(sysAuth.getAuthVersion());
        rowData.add(DateTool.formatDate(sysAuth.getAuthTime(), DateTool.FULL_TRADITION_PATTERN));
        rowData.add(StringTool.nullToEmpty(sysAuth.getAuthAvailable()));
        rowData.add(sysAuth.getAuthIp());
        rowData.add(sysAuth.getAuthAgent());
        return rowData;
    }
}
